package com.riaya.controller;

import com.mybatisflex.core.query.QueryWrapper;
import com.riaya.entity.Detail;
import com.riaya.entity.vo.DetailVo;
import com.riaya.model.R;
import com.riaya.mapper.GoodsMapper;
import com.riaya.mapper.SortMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.riaya.entity.table.DetailTableDef.DETAIL;
import static com.riaya.entity.table.SortTableDef.SORT;

/**
 * @Author: KAIyo
 * @Date: 2025/7/24 14:18
 * @Version: v1.0.0
 * @Description: TODO
 **/
@RestController
public class GoodController {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private SortMapper sortMapper;

    @GetMapping("/list")
    public R getGoodsList(@RequestParam(value = "sortId", required = false) Integer sortId){

        List<Detail> details;
        
        // 根据sortId参数决定查询所有商品还是特定分类的商品
        if (sortId == null || sortId == 0) {
            details = goodsMapper.selectAll();
        } else {
            QueryWrapper queryWrapper = QueryWrapper.create().select().where(DETAIL.SORT_ID.eq(sortId));
            details = goodsMapper.selectListByQuery(queryWrapper);
        }

        List<DetailVo> returnList = new ArrayList<>();
        details.forEach(detail -> {
            DetailVo detailVo = new DetailVo();
            QueryWrapper queryWrapper = QueryWrapper.create().select().where(SORT.ID.eq(detail.getSortId()));
            detailVo.setId(detail.getId());
            detailVo.setAddress(detail.getAddress());
            detailVo.setName(detail.getName());
            detailVo.setPrice(detail.getPrice());
            detailVo.setRemaining(detail.getRemaining());
            detailVo.setSortName(sortMapper.selectOneByQuery(queryWrapper).getName());
            detailVo.setCreateDate(detail.getCreateDate());
            detailVo.setSortId(detail.getSortId());
            returnList.add(detailVo);
        });

        return R.ok(returnList,"查询成功");
    }

    @GetMapping("/sortgood")
    public R getSortGoods(@RequestParam("sortId") Integer sortId){
        List<Detail> detailList = null;
        if (sortId == 0 || sortId == null){
            detailList = goodsMapper.selectAll();
        }else {
            QueryWrapper queryWrapper = QueryWrapper.create().select().where(DETAIL.SORT_ID.eq(sortId));
            detailList = goodsMapper.selectListByQuery(queryWrapper);
        }
        return R.ok(detailList);
    }

    @PostMapping("/drop")
    public R dropGoods(@RequestBody Detail detail){
        goodsMapper.update(detail);
        return R.ok("", "成功");
    }
}
